package org.xlx.xlx_oa.role_user.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.xlx.xlx_oa.common.Constant;
import org.xlx.xlx_oa.role_user.convertor.RoleUserConvertor;
import org.xlx.xlx_oa.role_user.domain.SysRoute;
import org.xlx.xlx_oa.role_user.domain.dto.SysRouteDto;
import org.xlx.xlx_oa.role_user.domain.vo.SysRouteVo;
import org.xlx.xlx_oa.role_user.mapper.SysRouteMapper;
import org.xlx.xlx_oa.utils.ThreadLocalUtil;

import java.util.List;
import java.util.Objects;

@Service
public class SysRouteService {
    private final RoleUserConvertor roleUserConvertor = RoleUserConvertor.INSTANCE;
    @Autowired
    private SysRouteMapper routeMapper;

    /**
     * 保存
     */
    public Boolean saveEntity(SysRouteVo routeVo) {
        SysRoute sysRoute = roleUserConvertor.convertVoToSysRoute(routeVo);
        Long id = sysRoute.getId();
        if (Objects.isNull(id)) {
            routeMapper.insert(sysRoute);
        } else {
            routeMapper.updateById(sysRoute);
        }
        return true;
    }

    /**
     * 删除
     */
    public Boolean removeEntity(Long id) {
        return routeMapper.deleteById(id) > 0;
    }

    /**
     * 获取路由
     *
     * @return
     */
    public List<SysRouteDto> getRoutes() {
        Object objUserId = ThreadLocalUtil.get(Constant.USERID);
        Long userId = Objects.isNull(objUserId) ? null : Long.valueOf(objUserId.toString());
        List<SysRoute> rootRoutes = routeMapper.selectListByUserId(userId);
        List<SysRouteDto> dtos = roleUserConvertor.convertToListSysRouteDto(rootRoutes);
        for (SysRouteDto dto : dtos) {
            this.getChildrenRoute(dto);
        }
        return dtos;
    }

    /**
     * 查找子路由
     *
     * @param route
     */
    public void getChildrenRoute(SysRouteDto route) {
        if (route.getIsLeaf()) {
            return;
        }
        QueryWrapper<SysRoute> wrapper = new QueryWrapper<>();
        wrapper.lambda()
                .eq(SysRoute::getParentId, route.getId())
                .eq(SysRoute::getOrderNo, route.getOrderNo() + 1)
                .orderByAsc(SysRoute::getId);
        List<SysRoute> sysRoutes = routeMapper.selectList(wrapper);
        route.setChildren(roleUserConvertor.convertToListSysRouteDto(sysRoutes));
        for (SysRoute sysRoute : sysRoutes) {
            this.getChildrenRoute(roleUserConvertor.convertToSysRouteDto(sysRoute));
        }
    }

}
